<?php
namespace app\user\admin;
use app\system\admin\Admin;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use think\Db;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCardDetailLog as UserCardDetailLogModel;
use app\shouyin\model\ProductOrder as ProductOrderModel;
use app\shouyin\model\Subscribe as SubscribeModel;
use app\user\model\User as UserModel;
use app\warehouse\model\Stock as StockModel;
use League\Csv\Reader;
class Records extends Admin
{
    public function initialize()
    {
		parent::initialize();
        $users = UserModel::field('id,nick')->all();
        $this->assign('users',UserModel::getSelect($users));

    }
    public function balance()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $start      = $this->request->param('start', '2000-01-01');
            $end        = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            // $where['user_id'] = $user_id;
            $data['data'] = UserBalanceLogModel::where($where)
                            ->where('createtime','between',[strtotime($start),strtotime($end)])
                            ->field('*,type as type_text')
                            ->page($page)
                            ->limit($limit)
                            ->order('id desc')
                            ->select();

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
            }
            $data['count'] = UserBalanceLogModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            $data['code'] = 0;

            return json($data);

        }
        return $this->fetch();
    }

    public function card()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['userid'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = UserCardDetailLogModel::where($where)
                    ->where('createtime','between',[strtotime($start),strtotime($end)])
                    ->order('id desc')
                    ->select();
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['userid'])->value('nick');
                    $data['data'][$key]['card_name'] = Db::name('project')->where('id',$value['cid'])->value('name');
                    switch ($value['type']) {
                        case 1:
                            $data['data'][$key]['type_text'] = '买入';
                            break;
                        case 2:
                            $data['data'][$key]['type_text'] = '使用';
                            break;

                        case 3:
                            $data['data'][$key]['type_text'] = '退卡';
                            break;
                    }
                }
                $data['count'] = UserCardDetailLogModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            }else{
                $data['data'] = UserCardDetailLogModel::where($where)
                    ->where('createtime','between',[strtotime($start),strtotime($end)])
                    ->page($page)
                    ->limit($limit)
                    ->order('id desc')
                    ->select();
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['userid'])->value('nick');
                    $data['data'][$key]['card_name'] = Db::name('project')->where('id',$value['cid'])->value('name');
                    switch ($value['type']) {
                        case 1:
                            $data['data'][$key]['type_text'] = '买入';
                            break;
                        case 2:
                            $data['data'][$key]['type_text'] = '使用';
                            break;

                        case 3:
                            $data['data'][$key]['type_text'] = '退卡';
                            break;
                    }
                }
                $data['count'] = UserCardDetailLogModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            }

            $data['code'] = 0;

            return json($data);

        }
        return $this->fetch();
    }

    public function card1()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = UserCardLogModel::field('pid,pid as pro_text,pid as price,user_id as user_name,COUNT(*) as num,type')
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                ->where($where)
                ->where('use',1)
                ->group('user_id,pid,type')
                ->select();

                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['type_name'] = $value['type'] == 1 ? '疗程卡' :'产品卡';

                }
                // halt($data['data']);
                $data['count'] = UserCardLogModel::where('createtime','between',[strtotime($start),strtotime($end)])->where($where)->where('use',1)->group('user_id,pid,type')->count('id');
            }else{
                $data['data'] = UserCardModel::where($where)
                    ->where('createtime','between',[strtotime($start),strtotime($end)])
                    ->page($page)
                    ->limit($limit)
                    ->order('id desc')
                    ->all();
                foreach ($data['data'] as $key => $value) {
                    $pro = [];
                    $data['data'][$key]['cardname'] = Db::name('course')->where('id',$value['course_id'])->value('name');
                    $data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
                    $data['data'][$key]['pro'] = UserCardLogModel::field('pid,pid as pro_text,count(pid) as num,type')->where('sn',$value['sn'])->where('use',1)->group('pid')->select()->toArray();

                }
                $data['count'] = UserCardModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            }

            $data['code'] = 0;

            return json($data);

        }
        return $this->fetch();
    }

    public function product()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }

            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = StockModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->where('detailed_type',2)
                                ->order('id desc')
                                ->select();


                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['user_name1'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
                    $data['data'][$key]['shop_name1'] = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                    $data['data'][$key]['ware_name1'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                }

                // halt($data);
                $data['count'] = count( $data['data']);
                $data['code'] = 0;
                return json($data);
            }else{

                $data['data'] = StockModel::where($where)
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                ->where('detailed_type',2)
                ->page($page)
                ->limit($limit)
                ->order('id desc')
                ->select();

                // SELECT * FROM `hisi_stock` WHERE  `createtime` BETWEEN 946656000 AND 1587883537  ORDER BY `id` DESC LIMIT 0,20
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['user_name1'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
                    $data['data'][$key]['shop_name1'] = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                    $data['data'][$key]['ware_name1'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                }
                $data['count'] = StockModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->where('detailed_type',2)->count('id');
                $data['code'] = 0;

                return json($data);
            }



        }
        return $this->fetch();
    }

    public function project()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);

            $user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            $SubscribeModel = new SubscribeModel;
            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = $SubscribeModel->where($where)
                ->where('status','<>',5)
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                // ->page($page)
                // ->limit($limit)
                ->order('id desc')
                ->select()->toArray();
            } else {
                $data['data'] = $SubscribeModel->where($where)
                ->where('status','<>',5)
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                ->page($page)
                ->limit($limit)
                ->order('id desc')
                ->select()->toArray();
            }


            // halt($SubscribeModel->getlastsql());
            $new_data = [];
            $i = 0;
            foreach ($data['data'] as $key => $value) {
                $shop_name = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                $room_name = Db::name('room')->where('id',$value['room_id'])->value('name');
                $username1 = Db::name('user')->where('id',$value['user_id'])->value('nick');
                $data['data'][$key]['project_data'] = json_decode($value['project_data'],true);
                // halt($data['data'][$key]['project_data']);

                if(!empty($data['data'][$key]['project_data'])){
                    foreach ($data['data'][$key]['project_data'] as $k => $v) {
                        if(isset($v['adviser_id'])){
                            $new_data[$i]['adviser_id'] = Db::name('system_user')->where('id',$v['adviser_id'])->value('nick');
                        }
                        $new_data[$i]['technician_ids'] = implode(',',Db::name('system_user')->where('id','in',$v['technician_ids'])->column('nick'));
                        $new_data[$i]['shop_name'] = $shop_name;
                        $new_data[$i]['room_name'] = $room_name;
                        $new_data[$i]['username1'] = $username1;
                        $new_data[$i]['sn'] = $value['sn'];
                        $new_data[$i]['createtime'] = $value['createtime'];
                        $new_data[$i]['project_name'] = $v['project_name'];
                        $new_data[$i]['num'] = $v['num'];
                        $new_data[$i]['price'] = $v['price'];
                        $new_data[$i]['is_give'] = $v['is_give'] == 2 ? '（赠送）' : '';
                        $i++;
                    }
                }

            }
            $data['data'] = $new_data;
            $data['count'] = $SubscribeModel->where($where)->where('status','<>',5)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            $data['code'] = 0;

            return json($data);

        }
        return $this->fetch();
    }

    public function import()
    {
        $model = new \app\common\model\SystemAnnex;
        $uploadFile = $model::fileUpload();
        // halt($uploadFile);
        if($uploadFile['code'] != 1){
            return $this->axiosMsg($uploadFile['msg'],false);
        }
        $filePath = $uploadFile['data']['file'];
        $reader = Reader::createFromPath('.'.$filePath, 'r');
        $records = $reader->getRecords();
        $newArr = [];
        foreach ($records as $offset => $record) {
            // var_export($record);
            // foreach ($record as $k => $v) {
            //     $record[$k][0] = iconv("GB2312//IGNORE", "UTF-8", $v[0]);
            //     $record[$k][3] = iconv("GB2312//IGNORE", "UTF-8", $v[3]);
            // }

            $newArr[] = $record;
        }
        unset($newArr[0]);

        $insertData = [];
        foreach ($newArr as $k => $v) {
            $sn = create_order_sn();
            if(!empty($v[1]) && $v[1] != 0){
                $insertData[] = [
                    'user_id' => $v[0],
                    'type' => 1,
                    'is_give' => 1,
                    'price' => $v[1],
                    'sn' => $sn,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
            }
            if(!empty($v[2]) && $v[2] != 0){
                $insertData[] = [
                    'user_id' => $v[0],
                    'type' => 1,
                    'is_give' => 2,
                    'price' => $v[2],
                    'sn' => $sn,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
            }
        }
        // halt($insertData);
        try {
            $ins = Db::name('user_balance_log')->insertAll($insertData);

        } catch (\Exception $e) {
            // echo Db::name('user_balance_log')->getlastsql();
            // SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row
            return  $this->axiosMsg($e->getMessage(),false);
        }
        return  $this->axiosMsg('录入成功！',true);
    }

}



 ?>
